﻿namespace MicroCloud.Identity.Events
{
    /// <summary>
    /// 用户登出事件：移除RefreshToken
    /// </summary>
    public class LogoutRemoveRefreshTokenEventHandler : EventHandlerBase<LogoutEventData>
    {
        //字段
        private readonly UserManager<User> _userManager;
        private readonly IPrincipal _principal;

        #region "构造函数"
        #region "初始化一个用户登出事件：移除RefreshToken的新实例"
        /// <summary>
        /// 初始化一个用户登出事件：移除RefreshToken <see cref="LogoutRemoveRefreshTokenEventHandler"/> 的新实例
        /// </summary>
        /// <param name="userManager"></param>
        /// <param name="principal"></param>
        public LogoutRemoveRefreshTokenEventHandler(UserManager<User> userManager, IPrincipal principal)
        {
            _userManager = userManager;
            _principal = principal;
        }
        #endregion

        #endregion

        #region "方法"
        #region "事件处理"
        /// <summary>
        /// 事件处理
        /// </summary>
        /// <param name="eventData">事件源数据</param>
        /// <param name="provider">服务提供者</param>
        public override void Handle(LogoutEventData eventData, IServiceProvider provider)
        {
            ClaimsIdentity identity = _principal.Identity as ClaimsIdentity;
            if (identity?.IsAuthenticated != true)
            {
                return;
            }

            string clientId = identity.GetClaimValueFirstOrDefault(ClaimTypeConstants.ClientId);
            if (clientId == null)
            {
                return;
            }

            _userManager.RemoveRefreshTokenAsync(eventData.UserId.ToString(), clientId).Wait();
        }
        #endregion

        #endregion

    }

}
